<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/9/12
 * Time: 23:34
 */

namespace app\index\domain;

use app\index\domain\BaseDomain;
use app\index\service\WeixinService;
use app\common\api\AccountApi;
use app\shop\api\MemberConfigApi;
use app\system\model\BoyeActionConst;
use app\system\model\OAuth2Type;
use app\system\model\UcenterMember;
use app\shop\api\RedEnvelopeApi;
use app\system\api\UserLogApi;

class WeixinDomain extends BaseDomain{

    private $appid;
    private $appsecret;

    public function __construct(){
        parent::__construct();
        //微信开放应用的appid和appsecret
        $this->appid     = "wxae95316b3a4998a6";
        $this->appsecret = "3d2aaf593b7a1d89bda2a206e7e536bb";
        $this->appid_web     = "wx673ef65eb4a7c8ff";
        $this->appsecret_web = "e194cb62e0ca66c74fc8d2b88ae9fe56";
    }

    /**
     * 微信绑定
     */
    public function bind(){
        $this->checkVersion($this->api_ver);
        $code =  $this->_post('code','','缺少code参数');
        $uid  =  $this->_post('uid','','缺少uid参数');
        addLog("Weixin/bind",$_GET,$_POST,"调用绑定接口CODE=".$code);

        $service = new WeixinService($this->appid,$this->appsecret);
        $result = $service->getUserInfo($code);

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }
        $weixin_userinfo = $result['info'];

        if(empty($weixin_userinfo)){
            $this->apiReturnErr("微信用户信息获取失败!");
        }

        $openid = $weixin_userinfo['openid'];
        $result = apiCall(AccountApi::GET_INFO_BY_WXOPENID,[$openid]);

        //如果已经存在，则返回信息
        if($result['status'] && is_array($result['info'])){
            if($result['info']['uid'] == $uid){
                $this->apiReturnSuc("绑定成功!");
            }

            $this->apiReturnErr("该微信已经绑定另一个账户!");
        }

        $entity = [
            'wxopenid'   =>$openid,
            'weixin_bind'=>1,
        ];

        $result = apiCall(MemberConfigApi::SAVE_BY_ID,[$uid,$entity]);

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }else{
            $this -> apiReturnSuc("绑定成功!");
        }
    }

    /**
     * 微信注册
     */
    public function login(){
        $this->checkVersion($this->api_ver);
        $code =  $this->_post('code','','缺少code参数');
        $from =  $this->_post('from','app');
        $device_type = $_POST['app_type'];
        addLog("Weixin/login",$_GET,$_POST,"调用微信登录接口CODE=".$code);

        if($from == 'app'){
        }elseif($from == 'pc'){
            $this->appid     = $this->appid_web;
            $this->appsecret = $this->appsecret_web;
        }else{
            $this->apiReturnErr('错误来源');
        }
        $service = new WeixinService($this->appid,$this->appsecret);
        $result = $service->getUserInfo($code);

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }

        $weixin_userinfo = $result['info'];

        addLog("Weixin/login",$weixin_userinfo,$weixin_userinfo,"微信登录拉取的用户信息");
        //注册用户账户

        $openid   = $weixin_userinfo['openid'];
        $password = $openid;
        $nickname = $weixin_userinfo['nickname'];
        $sex      = $weixin_userinfo['sex'];
        $city     = $weixin_userinfo['city'];
        $province = $weixin_userinfo['province'];
        $country  = $weixin_userinfo['country'];
        $head     = $weixin_userinfo['headimgurl'];
        $idcode   = getIDCode(rand(10000000000,99999999999),'X');

        $result = apiCall(AccountApi::GET_INFO_BY_WXOPENID,[$openid]);
        addLog("Weixin/login",$result,$result,"微信登录从数据库获取的用户信息".$openid);
        //如果已经存在，则返回信息
        if($result['status'] && is_array($result['info'])){
            $uid = $result['info']['uid'];
            $session_id = (new UcenterMember())->addLoginSession($uid, $device_type);
            $result['info']['login_session_code'] = $session_id;
            $this->apiReturnSuc($result['info']);
        }elseif($result['status'] === false){
            $this->apiReturnErr($result['info']);
        }

        $entity = [
            'type'          => UcenterMember::ACCOUNT_TYPE_USERNAME,
            'username'      => 'wx_'.md5($openid),
            'password'      => $password,
            'from'          => OAuth2Type::WEIXIN,
            'mobile'        => '',
            'realname'      => '',
            'nickname'      => '微信用户'.$nickname ,
            'email'         => '',
            'idnumber'      => '',
            'birthday'      => time(),
            'idcode'        =>$idcode,
            'head'          =>$head,
            //'weixin_bind' =>1, //绑定微信
            'wxopenid'      =>$openid,
        ];

        $trans = new \think\model\Adv();
        $trans->startTrans();
        $result = apiCall(AccountApi::REGISTER, [$entity]);

        if ($result['status']) {
            $uid = $result['info'];
            if($uid > 0){
                //注册红包
                $result = apiCall(RedEnvelopeApi::REG_ADD,[$uid]);
                if(!$result['status']) $flag = 1;

                //+score  +exp
                $result = apiCall(UserLogApi::REGISTER,[$uid,0]);
                if(!$result['status']) $this ->apiReturnErr($result['info']);
                $arr['msg'] = $result['info'];
                if($flag == 1){
                  $arr['msg']['err'][] = "注册红包发放失败,请联系管理员获取!";
                }else{
                  $arr['msg']['suc'][] = "注册红包发放";
                }
                // $this ->apiReturnSuc($arr);
                // if(!$result['status']) $flag = 1;
                $result = apiCall(AccountApi::GET_INFO,[$uid]);
                if($result['status']){
                    action_log(BoyeActionConst::API_USER_LOGIN, "member", $uid, $uid);
                    $result['info']['msg'] = $arr['msg'];
                    $trans->commit();
                    $session_id = (new UcenterMember())->addLoginSession($uid, $device_type);
                    $result['info']['login_session_code'] = $session_id;
                    $this->apiReturnSuc($result['info']);
                }
            }
        }
        $trans->rollback();
        $this->apiReturnErr($result['info']);
    }

}